﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using EasyBuyShop.Models;
using EasyBuyShop.DAL;

namespace EasyBuyShop.Controllers
{
    public class AuthController : Controller
    {
        private readonly ILogger<AuthController> logger;

        public AuthController(ILogger<AuthController> logger)
        {
            this.logger = logger;
        }

        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Login(User user)
        {
            var username =user.UserName;
            var password = user.Password;
            UserDal userDal = new UserDal();
            var user1 = userDal.GetUser(username, password);
            if (user1 != null)
            {
                HttpContext.Session.SetString("username", username);
                HttpContext.Session.SetString("realname", user1.RealName);
                HttpContext.Session.SetInt32("userid", user1.Id);

                var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, username));
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Sid, user1.Id.ToString()));
                var claimPrincipal = new ClaimsPrincipal(claimsIdentity);
                HttpContext.SignInAsync(claimPrincipal).Wait();
                return Redirect("/Home");
            }
            else
            {
                return View();
            }
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Register()
        {
            return View();
        }
    }
}
